package com.rankeiot.platform.service;

import com.rankeiot.core.util.JSONUtil;
import com.rankeiot.platform.config.WxOpenConfig;
import com.rankeiot.platform.vo.WxMpOAuth2AccessToken;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.http.HttpClient;
import java.util.Map;

/**
 * 微信开放平台服务
 */
@Component
@RequiredArgsConstructor
public class WxOpenService {
   final String OAUTH2_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
   final String USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";
   final RestTemplate template;
    /**
     * <pre>
     * 用code换取oauth2的access token
     * 详情请见: http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息
     * </pre>
     */
    public Map oauth2getAccessToken(String code) throws IOException {
        String url = String.format(OAUTH2_ACCESS_TOKEN_URL, WxOpenConfig.APP_ID.strValue(), WxOpenConfig.APP_SECRET.strValue(), code);
        Map result = JSONUtil.parseObject(get(url));
        return result;
    }

    /**
     * 获取用户个人信息（UnionID机制）
     * https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Authorized_Interface_Calling_UnionID.html
     * @param openid
     * @param accessToken
     * @return
     * @throws IOException
     */
    public Map userinfo(String openid,String accessToken) throws IOException {
        String url = String.format(USERINFO_URL, openid, accessToken);
        Map result = JSONUtil.parseObject(get(url));
        return result;
    }
    private String get(String url) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求类型为GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // 打印结果
        System.out.println(response.toString());
        return response.toString();
    }

}
